package h0909;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
  * @description 字符串解码
  * @author 不知名帅哥
  * @date 2024/9/9 16:20
  * @version 1.0
*/
public class DecodeString {
    public static void main(String[] args) {

    }

    public String decodeString(String s) {
        Deque<String> strStack=new LinkedList<>();
        Deque<Integer> numStack=new LinkedList<>();
        StringBuilder currentString=new StringBuilder();
        int currentNum=0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)){
                currentNum=0;
                while (Character.isDigit(s.charAt(i))){
                    currentNum=currentNum*10+(s.charAt(i)-'0');
                    i++;
                }
                i--;
                numStack.push(currentNum);
            }else if (c=='['){
                strStack.push(currentString.toString());
                currentString=new StringBuilder();
            }else if (c==']'){
                int repeatTimes=numStack.pop();
                //在原先的基础上再增加
                StringBuilder temp=new StringBuilder(strStack.pop());
                for (int j = 0; j < repeatTimes; j++) {
                    temp.append(currentString);
                }
                currentString=temp;
            }else {
                currentString.append(c);
            }
        }
        return currentString.toString();
    }
}
